<?php
session_start();
//require($_SERVER['DOCUMENT_ROOT'].'/DB.php');
require(dirname(__FILE__).'/DB.php');
require('../smarty/smarty_config.php');

$id = $_GET['id'];
$f = $_GET['f'];
if (empty($f) || empty($_SESSION['USER_ID'])) {
	header('location:index.php');
	exit;
}

$smarty -> display('./admin/header.tpl');
$smarty ->display('./admin/admin-left.tpl');

// setup a database connection
$db = new DB();
$db ->conn_mysql();

switch ($f) {
	// show the detail of the post with given indentity id
	case 'show':
		
		checkId($id);		
		$sql = 'select * from user where id = '.$id;
		echo $sql;
		$user_rec = $db ->run_sql_query($sql);
		$user_info = mysql_fetch_array($user_rec);
		if ($user_info){
			$smarty -> assign('user',$user_info);
		}
		$smarty ->display('./admin/user.tpl');

	// add a post
	case 'add':		
		if (empty($_POST['OP']) || $_POST['OP'] ='' ) {
			$smarty	-> assign('f','add');
			$smarty -> assign('id',$id);
			$smarty -> display('./admin/add-user.tpl');
			$smarty -> display('./admin/foot.tpl');
		} else if($_POST['OP'] = 'submit') {
			$sql = "insert into user values ('',now(),now(),'$_POST[user_name]',md5('$_POST[user_pwd]'),'$_POST[gender]','admin','1','$_POST[email]')";
			echo $sql;
			$result = $db -> run_sql_query($sql);
			if ($result) {
				
				$smarty -> display('./admin/response.tpl');
			}
		}
		
	// update a user
	case 'modify':			
		checkId($id);
		if (empty($_POST['OP'])){
			echo 'test';
			$sql = 'select * from user where id = '.$id;
			$user_rec = $db ->run_sql_query($sql);
			$user_info = mysql_fetch_array($user_rec);
			if ($user_info){
				$smarty	-> assign('f','modify');
				$smarty -> assign('id',$id);
				$smarty -> assign('user_info',$user_info);
				$smarty -> display('./admin/add-user.tpl');
			}
		}else if ($_POST['OP'] ='submit') {
			$sql = "update user set date_modified = now(),valid = $_POST[valid],user_name='$_SESSION[USER_NAME]' where id = $id";			
			echo $sql;
			$result = $db -> run_sql_query($sql);
			if ($result) {
				$smarty -> display('./admin/add-post-ok.tpl');
			}
		}
	// delete a post ,actully ,you know ,we always dont delete it ,just modify it.	
	case 'delete':
		checkId($id);
		$sql = "update user set valid =0 ,date_modified = now() where id = $id";			
		$result = $db -> run_sql_query($sql);
		if ($result) {
			$smarty -> display('./admin/add-post-ok.tpl');
		}
		
	case 'list':
		
		$sql = "select * from user";
		$users_res = $db -> run_sql_query($sql);
//		$users_info = mysql_fetch_array($users_res);
		while ($users_info = mysql_fetch_array($users_res)) {
			$users_list[] = $users_info;
		}
		$smarty -> assign('users_list',$users_list);
		$smarty -> display('./admin/admin-left.tpl');
		$smarty -> display('./admin/users-list.tpl');
		
	default:
		$smarty ->display('./admin/foot.tpl');
}



function checkId($id) {
	if (empty($id)) {
		header('location:index.php');
		exit;
	}
}